
#include "header/GloableFunction.h"
#include <memory.h>
#include "minilzo.h"
#include "header/ProtocolStruct.h"
#define MAX_COMPRESS_BUFF (1024*100)

bool CompressProtocol( BYTE* protocolBuff, unsigned int protocolLength, unsigned int protocolBuffLength, unsigned int headerLength)
{
	//ENTER_FUNCTION( TimeMeasureLogic_CompressProtocol );
	char compressBuff[MAX_COMPRESS_BUFF];
	memset(compressBuff, 0, sizeof(compressBuff));

	BYTE* pCompressBuff = (BYTE*)compressBuff;
	unsigned int compressBuffLength = MAX_COMPRESS_BUFF;
	BYTE* pCompressSrc = protocolBuff + headerLength;
	unsigned int compressSrcLength = protocolLength - headerLength;	
	lzo1x_1_compress(
		pCompressSrc,
		compressSrcLength,
		pCompressBuff,
		&compressBuffLength,
		wrkmem);

	if (compressBuffLength < protocolBuffLength - headerLength)
	{
		memcpy(pCompressSrc, pCompressBuff, compressBuffLength);
		COMPRESSED_PROTOCOL_HEADER* pProtocolHeader = (COMPRESSED_PROTOCOL_HEADER*)protocolBuff;
		pProtocolHeader->Length = compressBuffLength + headerLength - 1;

		return true;
	}
	else
	{
		return false;
	}
}

bool DecompressProtocol(const BYTE* compressedProtocolBuff, BYTE* decompressBuff, unsigned int decompressBuffLength, unsigned int headerLength)
{
	memset(decompressBuff, 0, decompressBuffLength);
	memcpy(decompressBuff, compressedProtocolBuff, headerLength);
	COMPRESSED_PROTOCOL_HEADER *pProtocolHeader = (COMPRESSED_PROTOCOL_HEADER*)decompressBuff;

	const BYTE* pCompressedBuff = compressedProtocolBuff + headerLength;
	unsigned int compressedBuffLength = pProtocolHeader->Length + 1 - headerLength;
	BYTE* pDecompressBuff = decompressBuff + headerLength;
	unsigned int realDecompressBuffLength = decompressBuffLength - headerLength;
	lzo1x_decompress(
		pCompressedBuff,
		compressedBuffLength,
		pDecompressBuff,
		&realDecompressBuffLength,
		NULL);

	pProtocolHeader->Length = realDecompressBuffLength + headerLength - 1;

	return (realDecompressBuffLength < decompressBuffLength - headerLength);
}